﻿
namespace CmdArgs.Settings
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using CmdArgs.Utils;

    /// <summary>
    /// Represents settings for command line arguments parsing process.
    /// The settings object consists of list of OptionSettings and 
    /// provide also methods for outputting the help for user.
    /// </summary>
    public sealed class Settings
    {
        private IDictionary<string, OptionSettings> optionsSettings = new Dictionary<string, OptionSettings>();

        /// <summary>
        /// Initializes a new instance of the <see cref="Settings"/> class.
        /// </summary>
        /// <param name="optionsSettings">The options settings.</param>
        internal Settings(IEnumerable<OptionSettings> optionsSettings)
        {
            this.OptionsSettings = optionsSettings.Copy();
            foreach (var anOptionSettings in optionsSettings)
            {
                foreach (var name in anOptionSettings.GetAllNames())
                {
                    this.optionsSettings[name] = anOptionSettings;
                }
            }
        }

        /// <summary>
        /// Gets the list of options settings.
        /// </summary>
        public IEnumerable<OptionSettings> OptionsSettings { get; private set; }

        /// <summary>
        /// Gets the settings of option which has one of it's long or short aliases equals to given name.
        /// </summary>
        /// <param name="optionName">Name of the option, it may be long name alias or short name alias.</param>
        /// <returns>The option's settings or null if not found.</returns>
        public OptionSettings GetOptionSettings(string optionName)
        {
            OptionSettings result = null;
            this.optionsSettings.TryGetValue(optionName, out result);
            return result;
        }

        /// <summary>
        /// Writes the help for user to given text writer.
        /// </summary>
        /// <param name="writer">The writer for output.</param>
        public void WriteHelpTo(TextWriter writer)
        {
            foreach (var optionSettings in this.OptionsSettings)
            {
                optionSettings.WriteHelpTo(writer);
                writer.WriteLine();
            }
        }

        /// <summary>
        /// Writes the help to console standard output.
        /// </summary>
        public void WriteHelpToConsole()
        {
            this.WriteHelpTo(Console.Out);
        }
    }
}
